/**************************************工具 START***********************/
(function ($) {
    // 默认参数
    var defaults =
	{
	    // 鼠标遮罩层样式
	    shadecolor: "#FFD24D",
	    shadeborder: "#FF8000",
	    shadeopacity: 0.5,
	    cursor: "move",

	    // 大图外层样式
	    layerwidth: 400,
	    layerheight: 300,
	    layerborder: "#DDD",
	    fade: true,

	    // 大图尺寸
	    largewidth: 1280,
	    largeheight: 960
	}

    // 插件入口
    var enlarge = function (option) {
		
        // 合并参数
        option = $.extend({}, defaults, option);
       
		var self = $(this).css("position", "relative").css("float","left");
		
		var img = self.children().first();
		
		// 计算大小图之间的比例
		var ratio =
		{
			x: img.width() / option.largewidth,
			y: img.height() / option.largeheight
		}
		
		// 定义一些尺寸
		var size =
		{
			// 计算鼠标遮罩层的大小
			shade:
			{
				width: option.layerwidth * ratio.x - 2,
				height: option.layerheight * ratio.y - 2
			}
		}
		
		
		// 创建鼠标遮罩层
		var shade = $("<div>").css(
		{
			"position": "absolute",
			"left": "0px",
			"top": "0px",
			"background-color": option.shadecolor,
			"border": "1px solid " + option.shadeborder,
			"width": size.shade.width,
			"height": size.shade.height,
			"opacity": option.shadeopacity,
			"cursor": option.cursor
		});
		shade.hide().appendTo(self);

		// 创建大图和放大图层
		var large = $("<img>").css(
		{
			"position": "absolute",
			"display": "block",
			"width": option.largewidth,
			"height": option.largeheight
		});
		var layer = $("<div>").css(
		{
			"position": "absolute",
			"left": self.width() + 5,
			"top": 0,
			"background-color": "#FFF",
			"overflow": "hidden",
			"width": option.layerwidth,
			"height": option.layerheight,
			"border": "1px solid " + option.layerborder,
			"z-index":999
		});
		large.attr("src", img.attr("data-big"));
		large.appendTo(layer);
		layer.hide().appendTo(self);

		// 不可移动的半径范围
		var half =
		{
			x: size.shade.width / 2,
			y: size.shade.height / 2
		}

		// 有效范围
		var area =
		{
			width: self.innerWidth() - shade.outerWidth(),
			height: self.innerHeight() - shade.outerHeight()
		}

		// 对象坐标
		var offset = self.offset();

		// 显示效果
		var show = function () {
			offset = self.offset();
			shade.show();
			if (option.fade) layer.stop().fadeIn(300);
			else layer.show();
		}

		// 隐藏效果
		var hide = function () {
			shade.hide();
			layer.hide();
		}

		// 绑定鼠标事件
		self.mousemove(function (e) {
			
			// 鼠标位置
			var x = e.pageX - offset.left;
			var y = e.pageY - offset.top;

			// 不在图像中则直接隐藏
			if (x < 0 || x > self.innerWidth()) return hide();
			if (y < 0 || y > self.innerHeight()) return hide();

			// 判断是否在有效范围内
			x = x - half.x;
			y = y - half.y;

			if (x < 0) x = 0;
			if (y < 0) y = 0;
			if (x > area.width) x = area.width;
			if (y > area.height) y = area.height;

			// 遮罩层跟随鼠标
			shade.css(
			{
				left: x,
				top: y
			});

			// 大图移动到相应位置
			large.css(
			{
				left: (0 - x / ratio.x),
				top: (0 - y / ratio.y)
			});
		})
		.mouseenter(show)
		.mouseleave(hide);
		
		// 提供接口 修改图片的url
		var plugin = {
			"_img":img,
			"_large":large,
			"changeUrl":function(middleUrl,bigUrl){
				//先缓存图片
				this._cacheImg(middleUrl);
				this._cacheImg(bigUrl);
				this._img[0].src = middleUrl;
				//设置大图url
				this._img.attr('data-big',bigUrl);
				//设置大图
				this._large[0].src = bigUrl;
			},
			"_cacheImg":function(url){
				var isExist = false;
				$(".j_caImg").each(function(index,ele){
					if($(ele).attr("src")==url)isExist = true;
				});
				if(!isExist){
					$("<img>").css({"display": "none","width":0,"height": 0}).attr("src",url).addClass("j_caImg").appendTo($('body'));
				}
			}
		};
		
		return plugin;
    }

    // 扩展插件
    $.fn.extend(
	{
	    enlarge: enlarge
	});
    
    
})(jQuery);

//图片列表滚动组件
(function ($){
	var defaultOption = {
		count:5,
		mouseover:function(){return true;}
	}
	//封装 小图列表滚动事件
	var imgslider = function(option){
		option = $.extend({}, defaultOption, option);
		var $that = this;
		var displayCount = option.count;
		var stopNextIndex = $that.find('.j_img-items li').length - displayCount;/** 显示 5张图片**/
		//初始化 上一个下一个 是否能点
		$that.find('.j_img-prev').addClass('j_disabled');
		if(stopNextIndex < 1){ //图片数目小于要展示的5张图片时，设置不能下一张
			 $that.find('.j_img-next').addClass('j_disabled');
		}
		
		var firstLi = $that.find(".j_img-items li:first");
		//动态计算每次移动的距离
		var interval = firstLi.width()+parseInt(firstLi.css("margin-left")) + parseInt(firstLi.css("margin-right"));
		//console.log(parseInt($(".j_img-items li").css("border-left-width"))) 边框宽度
		var curIndex = 0;
		var silder = $that.find('.j_scrollbutton');
		
		silder.click(function(){
			if( $(this).hasClass('j_disabled') ) return false;
			if ($(this).hasClass('j_img-prev')) --curIndex;
			else ++curIndex;
			silder.removeClass('j_disabled');
			if (curIndex == 0)  $that.find('.j_img-prev').addClass('j_disabled');
			if (curIndex == stopNextIndex)  $that.find('.j_img-next').addClass('j_disabled');
			$(".j_img-items ul").stop(false, true).animate({"marginLeft" : -curIndex*interval + "px"}, 200);
		});	
		
		$that.find('.j_img-items li img').bind("click", function(){}).bind("mouseover", function(){
			if (!$(this).parent().hasClass('img-hover')) {
					var that = this;
					if(option.mouseover){
						if(option.mouseover(that)){
							//先清除所有的样式
							$(that).parent().siblings().removeClass('img-hover');
							$(that).parent().addClass('img-hover');
						};
					}
			}

		}).bind("mouseout", function(){});  
	
	};
	
	 // 扩展插件
    $.fn.extend({imgslider: imgslider});
   
})(jQuery);

/**************************************工具END****************************************************/

/************************************** productMain  START**************************************/

Comps.Productmain = function(option){
	this.compId = option.compId;
	this.showMarketPrice = option.showMarketPrice;
	this.showAppraise = option.showAppraise;
	this.showBuy = option.showBuy;
	this.showStock = option.showStock;
	this.needAsyncInit = option.needAsyncInit;
	//加入购物车发布的主题名称
	this.cartEventTopic = option.cartEventTopic;
	//购买时 要求登陆的主题名称
	this.loginTopic = option.loginTopic;
	//运行期商品ID从URL中获取
	this.productUuid = this.getQueryString("productUuid");
	if(this.productUuid == null){
		//预览时  从属性配置中获取
		this.productUuid  = option.productUuid;
	}
}


Comps.Productmain.prototype.getQueryString = function(name){
	 var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}

Comps.Productmain.prototype.init = function(){
	var that = this;
	
	//检查必选参数
	if(!this.checkProductUuid()){
		Utils.ajaxLoadComplate(that);//去掉遮罩
		return;
	}
	
	//1.是否懒加载，如果是懒加载，则下面数据通过ajax请求，渲染html页面
	if(this.needAsyncInit){
		// ajax先生成html页面，然后在初始化效果组件
		$.ajax({
			url:ContextPath+"/productmain/getInitData",
			data:{productUuid: this.productUuid},
			method:"GET",
			dataType: "json",
			success:function(data){
				if(data.productUuid!= null && data.productUuid!= undefined && data.poductUuid!=""){
					//生成页面
					that.genCompHtml(data);
					//初始化事件
					that.initEvents();
					
					//进入页面，添加浏览足迹
					that.viewRecords(data);
				}else{
					$("#"+that.compId).html("<p style='text-align: center;color: red'>请配置 正确的预览参数[商品UUID]</p>");
				}
				Utils.ajaxLoadComplate(that);
				
				
			},error:function(e){
				console.log("懒加载数据格式出现错误");
			}
		});
	
	}else{
		//同步加载，后台生成页面
		//初始化事件
		$(document).ready(function(){
			var viewRecordStr = $("#"+that.compId).attr("data-viewRecord");
			if(viewRecordStr && viewRecordStr!=""){
				var viewRecord  = JSON.parse(viewRecordStr);
				that.viewRecords(viewRecord);
			}
			that.initEvents();
			Utils.ajaxLoadComplate(that);
		});
		
	}
	
}


Comps.Productmain.prototype.checkProductUuid = function(){
	var compId = this.compId;
	if(this.productUuid!= null && this.productUuid!= undefined && this.poductUuid!=""){
		return true;
	}else{
		$("#"+compId).html("<p style='text-align: center;color: red'>请配置 预览参数[商品UUID]</p>");
		return false;
	}
}

Comps.Productmain.prototype.viewRecords = function(data){
		var that = this;
		var product = {};
		product.productUuid = data.productUuid;
		product.productName = data.productName;
		product.bigImageUrl = data.bigImageUrl;
		product.shopPrice = data.shopPrice;
		product.saleCount = data.saleCount;
		product.privilegeTypes = ["1"];////????
		that.saveViewRecords(product);

}

//保存浏览足迹
Comps.Productmain.prototype.saveViewRecords = function(productDetailInfo){
	 var viewRecords = localStorage.getItem('_viewRecords2');
	 if(viewRecords != null && viewRecords != ""){
		 var viewRecordsArray = JSON.parse(viewRecords);
		 var productUuid = productDetailInfo.productUuid;
		 localStorage.setItem('productUuid',productUuid);
		 if(viewRecordsArray[productUuid] == null){
   		 	viewRecordsArray[productUuid] = productDetailInfo;
   		 	localStorage.setItem('_viewRecords2',JSON.stringify(viewRecordsArray));
		 }

	 }else{
		 var viewRecordsArray = {};
		 var productUuid = productDetailInfo.productUuid
		 if(viewRecordsArray[productUuid] == null){
			 viewRecordsArray[productUuid] =  productDetailInfo;
   		 	 localStorage.setItem('_viewRecords2',JSON.stringify(viewRecordsArray));
		 }

	 }
}



Comps.Productmain.prototype.genCompHtml = function (data){
	var compId = this.compId;
	//生成左侧图片列表
	var ulELe = $("#"+compId+"_img-items ul");
	var liEle  = ulELe.find("li:first");
	liEle.remove();//移除模板
	
	//第一张主图
	$("#"+compId+"_mid").attr("src",data.centerImageUrl).attr("data-big",data.bigImageUrl);
	var firstLi = liEle.clone();
	firstLi.find("img").attr("src",data.smallImageUrl).attr("data-mid-url", data.centerImageUrl).attr("data-big-url", data.bigImageUrl);
	ulELe.append(firstLi);
	//其他多视角图片
	if(data.imgList && data.imgList != null){
		$.each(data.imgList,function(index,one){
			var tmpLi = liEle.clone();//克隆模板，填充数据，然后追加到ul下
			tmpLi.find("img").attr("src",one.smallImageUrl).attr("data-mid-url", one.centerImageUrl).attr("data-big-url", one.bigImageUrl);
			ulELe.append(tmpLi);
		});
	}

	
	//生成右侧主信息页面
	if(!data.isSelfStore)$("#"+compId+"_selfStore").remove();
	$("#"+compId+"_productName").html(data.productName);
	$("#"+compId+"_note").html(data.adviceNote);
	//是否显示市场价
	if(this.showMarketPrice){
		$("#"+compId+"_marketPriceValue").html(data.marketPrice);
	}else{
		$("#"+compId+"_marketPrice").remove();
	}
	//商城价格
	$("#"+compId+"_shopPrice").html(data.shopPrice);
	//商品评价
	if(this.showAppraise){
		$("#"+compId+"_appraise").css("width",data.productScore*20 + "%");
		$("#"+compId+"_appCount").html(data.appCount);
	}else{
		$("#"+compId+"_productAppCount").remove();
	}
	
	//生成库存
	this.genStock(data);
	//显示立即购买按钮
	this.genFastBuy(data);
	//生成 商品规格属性
	this.genAttriubte(data);
	
}

//生成库存
Comps.Productmain.prototype.genStock= function(data){
	var compId = this.compId;
	//显示库存
	$("#"+compId+"_number").attr("data-stock",data.stock);
	if(this.showStock){
		$("#"+compId+"_stock").html(data.stock);
	}else{
		$("#"+compId+"_stockNode").remove();
	}
	if(data && data.stock < 1){
		//无库存，置灰购买按钮和加入购物车 
		$("#"+compId+"_fastBuy").prop("disabled",true);
		$("#"+compId+"_addtocar").prop("disabled",true);
	}
}
//购买按钮和加入购物车
Comps.Productmain.prototype.genFastBuy= function(data){
	var compId = this.compId;
	if(this.showBuy){
		
	}else{
		$("#"+compId+"_fastBuy").remove();
	}
}

//生成选择规格属性
Comps.Productmain.prototype.genAttriubte= function(data){
	var compId = this.compId;
	//初始化表单数据
	this.genInitFormData(data);
	var ulELe = $("#"+compId+"_productAttributes");
	var liEle  = ulELe.find("li:first");
	liEle.remove();//移除模板
	if(data.productAttributes && data.productAttributes != null){
		$.each(data.productAttributes,function(index,obj){
			var tmpLi = liEle.clone();//克隆模板，填充数据，然后追加到ul下 
			var attrValsDiv = tmpLi.find(".j_attributesValues");
			var spanEle = tmpLi.find(".j_valuespan");
			spanEle.remove();
			if(obj.canColor =="0"){
				tmpLi.find(".j_attributeName").html(obj.attributeName);
				$.each(obj.values,function(ind,val){
					var tmpSpan = spanEle.clone();
					if($.inArray(val.valueUuid,data.initSelectSpecUuids) != -1){
						tmpSpan.addClass('active');
						//父类加上已选择的uuid,以便事件处理
						tmpLi.attr("data-selectValueUuid",val.valueUuid);
					}
					tmpSpan.find(".j_attributeValue").attr("data-valueUuid",val.valueUuid).html(val.value);
					attrValsDiv.append(tmpSpan);
				});
				ulELe.append(tmpLi);
			}
		});
	}

}

//初始化商品购买表单
Comps.Productmain.prototype.genInitFormData= function(data){
	var compId = this.compId;
	var form = $("#"+compId+"_pForm");
	var specSize = data.initSelectSpecUuids.length;
	form.find("#"+compId+"_skuNo").val(data.skuNo);
	form.find("#"+compId+"_specSize").val(specSize);
	if(specSize > 0){
		for(var i = 0 ;i < specSize ; i++){
			form.find("#"+compId+"_specUuid"+i).val( data.initSelectSpecUuids[i]);
		}
	}
	form.find("#"+compId+"_productUuid").val(data.productUuid);
	form.find("#"+compId+"_productType").val(data.productType);
}



//组件事件
Comps.Productmain.prototype.events = {}

Comps.Productmain.prototype.events.fastBuy = function(comp){
	var compId = comp.compId;
	if(comp.loginTopic){
		CompMessage.publish(comp.loginTopic,{},function(){
			$("#"+compId+"_pForm").submit() ;
		});
	}
}
//减少按钮事件
Comps.Productmain.prototype.events.reduceNumber = function(comp){
	var compId = comp.compId;
	$number = 	$("#"+compId+"_number");
	var number = parseInt($number.val());
	if(number == 1 || number < 2){
		return;
	}
	$number.val(--number);
}
//增加按钮事件
Comps.Productmain.prototype.events.addNumber = function(comp){
	var compId = comp.compId;
	$number = 	$("#"+compId+"_number");
	var number = $number.val();
	if(comp.showStock){
		var stock = parseInt($number.attr("data-stock"));
		if(number >= stock){
			$number.val(stock);
		}else{
			$number.val(++number);
		}
	}else{
		$number.val(++number);
	}
}

//数量输入框 填写事件
Comps.Productmain.prototype.events.inputNumber = function(comp,e){
	   var input = $(e.target);
	   var number = input.val();
	   var stock = parseInt(input.attr('data-stock'));
	   try{
		   number = parseInt(number);
		   if(isNaN(number)){
			   number = 1;
		   }
	   }catch(e){
		   number = 1;
	   }
	   if((number > stock) & comp.showStock)number = stock;
	   input.val(number);
}

//加入购物车
Comps.Productmain.prototype.events.addToCart = function(comp){
	var compId = comp.compId;
	var skuNo = $("#"+compId+"_skuNo").val();
	var buyNum = $("#"+compId+"_number").val();
	data = {
			"attrIds":skuNo,
			"productUuid":comp.productUuid,
			"buyNum":buyNum,
			"time":new Date().getTime()
	};
	$.ajax({
		url:ContextPath+"/cart/addtocart",
		data:data,
		method:"GET",
		success:function(data){
				if(comp.cartEventTopic){
					//加入购物车成功后，发布购物车消息
					CompMessage.publish(comp.cartEventTopic,{});
				}
				//有侧边栏购物车的时候 才有飞入效果
				if($(".y_rtcart").length > 0){
					//购物车飞入效果
					var this_x = $("#"+compId+"_addtocar").offset().left + $("#"+compId+"_addtocar").width()/2,
					this_y = $("#"+compId+"_addtocar").offset().top- $(window).scrollTop() - 50;

					$("#"+compId+"_mid").shoping({
						buyNum:buyNum,
						star_x:this_x,//飞入元素的起点x轴位置
						star_y:this_y//飞入元素的起点y轴位置
					});
				}
			
		},error:function(e){
			console.log("加入购物车出现错误");
		}
	});
}


//2.初始化插件,功能
Comps.Productmain.prototype.initEvents=function(){
	var compId = this.compId;
	var that = this;
	var productUuid = this.productUuid;
	//初始化放大器事件
	var height =$("#"+compId).find(".j_preview").height();
	var plugin = $("#"+compId+"_bigImgWrap").enlarge(
	{
		// 鼠标遮罩层样式
		shadecolor: "#FFD24D",
		shadeborder: "#FF8000",
		shadeopacity: 0.4,
		cursor: "move",

		// 大图外层样式
		layerwidth: height,
		layerheight: height,
		layerborder: "#DDD",
		fade: true,

		// 大图尺寸
		largewidth: 740,
		largeheight: 740
	});
		
	
	//初始化小图列表鼠标移动事件
	$("#"+compId+"_imgSlider").imgslider({
		mouseover:function(obj){
			plugin.changeUrl($(obj).attr("data-mid-url"),$(obj).attr("data-big-url"));
			return true;
		}
	});
	
	
	// 减少按钮事件
	$("#"+compId+"_reduce").click(function(){
		that.events.reduceNumber(that);
	});
	
	//增加按钮事件
	$("#"+compId+"_add").click(function(){
		that.events.addNumber(that);
	});
	
	//输入框事件
	$("#"+compId+"_number").bind('input propertychange', function(e) {  
		that.events.inputNumber(that,e);
	});
	
	//选择规格属性事件,选择规格属性后动态改变价格和库存
	$("#"+compId+"_productAttributes").find(".j_attributeValue").click(function(){
		var selectUuid = $(this).attr("data-valueUuid");
		//设置该属性已选择的UUid为 selectUuid
		var parentLi = $(this).parents("li.j_chooseAttribute");
		parentLi.attr("data-selectValueUuid",selectUuid);
		parentLi.find(".j_valuespan").removeClass('active');
		$(this).parent().addClass('active');
		
		//获取所有已选择的规格属性
		var noSelectMsg = [];
		var  form = $("#"+compId+"_pForm");
		var selectedUuids = parentLi.parent().find("li.j_chooseAttribute").map(function(index,liEle){
			var selectedUuid = $(liEle).attr("data-selectValueUuid");
			if(selectedUuid && selectedUuid!= ""){
				//已经选择的 给表单赋值,购买时提交表单需要此数据
				form.find("#"+compId+"_specUuid"+index).val(selectedUuid);
				return selectedUuid;
			}else{
				noSelectMsg.push($(liEle).find('.j_attributeName').html());
				return false ;
			}
		}).get();
		//所有规格已经选择，提交后台获取库存价格等信息
		if($.inArray(false,selectedUuids) == -1){
			$.getJSON(ContextPath+"/productmain/selectSpec",
				{productUuid:productUuid, selectUuids : selectedUuids.join("-")},
				function(data){
					// 动态修改价格和库存
					//设置价格
					$("#"+compId+"_shopPrice").html(data.selecSpceData.price);
					//设置SKU
					$("#"+compId+"_skuNo").val(data.selecSpceData.skuNo);
					//设置库存
					$("#"+compId+"_number").attr("data-stock",data.selecSpceData.stock);
					if(that.showStock){
						var stock = parseInt(data.selecSpceData.stock);
						$("#"+compId+"_stock").html(stock);
						if(stock <= 0 ){
							//没有库存，不可购买
							$("#"+compId+"_addtocar").prop("disabled",true);
							if($("#"+compId+"_fastBuy")){
								$("#"+compId+"_fastBuy").prop("disabled",true);
							}
						}else{
							$("#"+compId+"_addtocar").prop("disabled",false);
							if($("#"+compId+"_fastBuy")){
								$("#"+compId+"_fastBuy").prop("disabled",false);
							}
						}
					}
					
					//修改图片显示
					plugin.changeUrl(data.selecSpceData.centerPictureUrl,data.selecSpceData.bigPictureUrl);
				});
		}else{
			console.log("未选择："+noSelectMsg);
		}
		
	});
	
	//立即购买事件
	$("#"+compId+"_fastBuy").on('click',function(){
		that.events.fastBuy(that);
	});
	$("#"+compId+"_addtocar").on('click',function(){
		that.events.addToCart(that);
	});
	
}



/************************************** productMain END **************************************/

/************************************** productGroup START **************************************/
//js float计算工具对象
var floatCalFun = {
	//获取参数精度，如果为整数则精度为0
	_getPrecision:function(arg){
		if(arg.toString().indexOf(".")==-1){
			return 0;
		}else{
			return arg.toString().split(".")[1].length;
		}
	},
	//获取小数的整数形式
	_getIntFromFloat:function(arg){
		if(arg.toString().indexOf(".") == -1){
			return arg;
		}else{
			return Number(arg.toString().replace(".",""));
		}
	},
	floatMulti:function(arg1,arg2){
		 var precision1 = this._getPrecision(arg1);
		 var precision2 = this._getPrecision(arg2);
		 var tempPrecision = 0;

		tempPrecision += precision1;
		tempPrecision += precision2;
		 var int1 = this._getIntFromFloat(arg1);
		 var int2 = this._getIntFromFloat(arg2);
		 return (int1*int2)*Math.pow(10,-tempPrecision);
	},
	floatAdd:function(arg1,arg2){
		 var precision1 = this._getPrecision(arg1);
		 var precision2 = this._getPrecision(arg2);
		 var temp = Math.pow(10,Math.max(precision1,precision2));
		 return (this.floatMulti(arg1,temp) + this.floatMulti(arg2,temp))/temp;
	},
	//减法   arg1 被减数  arg2 减数
	floatSubtract:function(arg1,arg2){
		 var precision1 = this._getPrecision(arg1);
		 var precision2 = this._getPrecision(arg2);
		 var temp = Math.pow(10,Math.max(precision1,precision2));
		 return (this.floatMulti(arg1,temp)-this.floatMulti(arg2,temp))/temp;
	},
	//除法 arg1 被除数 arg2 除数
	floatDiv:function(arg1,arg2){
		 var precision1 = this._getPrecision(arg1); 
		 var precision2 = this._getPrecision(arg2); 
		 var int1 = this._getIntFromFloat(arg1); 
		 var int2 = this._getIntFromFloat(arg2); 
		 var result = (int1/int2)*Math.pow(10,precision2-precision1); 
		 return result; 
	}
}

//声明商品组合 组件
Comps.Productgroup = function(option){
	this.compId = option.compId;
	this.needAsyncInit = option.needAsyncInit;
	this.productDetailUrl = option.productDetailUrl;
	this.loginTopic = option.loginTopic;
	
	//运行期商品ID从URL中获取
	this.productUuid = this.getQueryString("productUuid");
	if(this.productUuid == null){
		//预览时  从属性配置中获取
		this.productUuid  = option.productUuid;
	}
}

Comps.Productgroup.prototype.getQueryString = function(name){
	 var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}

//组件渲染
Comps.Productgroup.prototype.init = function(){
	var compId = this.compId;
	var productUuid = this.productUuid;
	var that = this;
	//从跟组件跟节点 读取配置
	//判断是 同步加载还是异步加载，以及是否使用本地数据
	if(this.needAsyncInit){
		$.getJSON(ContextPath+"/productgroup/getInitData",
			{productUuid:productUuid},
			function(data){
				if(data && data.groupList && data.groupList.length > 0){
					//生成页面HTML
					that._genHtml(data);
					//设置组件展示
					$("#"+compId).css("display","block");
					//初始化组件事件
					that._initCompEvents();
					
					Utils.ajaxLoadComplate(that);
				}else{
					//如果没有商品最后，要移除该组件
					$("#"+compId).remove();
				}
			});
	}else{//后台生成
		var hasData = $("#"+compId).attr("data-has");
		if(hasData == "1"){//有数据则展示组件，否则不展示
			$("#"+compId).css("display","block");
			//初始化组件事件
			that._initCompEvents();
		}
		Utils.ajaxLoadComplate(that);
	}
	
	return 	this;

}

//生成html
Comps.Productgroup.prototype._genHtml=function(data){
	var compId = this.compId;
	//存储商品数据，用于选择组合商品计算价格
	 $("#"+compId).attr("marketPrice",data.marketPrice);
	 $("#"+compId).attr("shopPrice",data.shopPrice);
	
	var ulEle = $("#"+compId+"_tab").find(".j_tab-itmes");
	var liEle = ulEle.find(".j_tab-item");
	liEle.remove();
	
	//生成tab页签
	$.each(data.groupList,function(index,productgroup){
		var tempLi = liEle.clone();
		if(index==0)tempLi.addClass('active');
		tempLi.find(".j_groupName").attr("href","#"+compId+"_group_"+productgroup.groupUuid).html(productgroup.groupName);
		ulEle.append(tempLi);
	});
	
	//生成tab页内容
	this._genTabContent(data);
	
	//初始化价格信息
	this._initPrice(data);

}

//生成标签页内容
Comps.Productgroup.prototype._genTabContent= function(data){
	var that = this;
	var compId = this.compId;
	var tabContent = $("#"+compId+"_tab-content");
	var divEle = tabContent.find(".j_content-item");
	divEle.remove();
	$.each(data.groupList,function(index,productgroup){
		var tempDiv = divEle.clone();
		tempDiv.attr("id",compId+"_group_"+productgroup.groupUuid);
		//默认第一个页签active
		if(index==0)tempDiv.addClass('active');
		//设置第一张图的src和价格
		var defaultProduct = tempDiv.find('.j_default-product');
		defaultProduct.find('.j_img').attr('src',data.centerImageUrl);
		defaultProduct.find('.j_price').html("¥"+data.shopPrice);
		
		//生成中间推荐的子商品列表
		var subProducts = tempDiv.find('.j_sub-products');
		var subUlEle  = subProducts.find('.j_subs');
		var subLiEle = subUlEle.find('.j_sub-item');
		subLiEle.remove();
		$.each(productgroup.subProducts,function(ind,subProduct){
			//设置商品数据
			var tempSubLiEle = subLiEle.clone();
			tempSubLiEle.data('subProduct',subProduct);
			
			//设置图片和商品名称链接地址productDetailUrl
			var productLink = tempSubLiEle.find('.j_productLink');
			var productLinkStr = ContextPath + that.productDetailUrl+"&productUuid="+subProduct.productUuid;
			productLink.attr("href",productLinkStr);
			tempSubLiEle.find('.j_productLink2').attr("href",productLinkStr);
			//设置图片地址，商品名，以及价格
			if(subProduct.centerImage)tempSubLiEle.find('.j_sub-img').attr('src',subProduct.centerImage);
			tempSubLiEle.find('.j_sub-productName').html(subProduct.productName);
			tempSubLiEle.find('.j_sub_price').html("¥"+subProduct.shopPrice);
			
			subUlEle.append(tempSubLiEle);
		});
		
		tabContent.append(tempDiv);
	});

}

//初始化价格
Comps.Productgroup.prototype._initPrice= function(data){
	var compId = this.compId;
	var compRoot = $("#"+compId);
	var allShopPrice = parseFloat(compRoot.attr("shopPrice"));
	
	compRoot.find('.j_selectedPrice').html("¥"+allShopPrice);

}

//初始化事件
Comps.Productgroup.prototype._initCompEvents =function(){
	var that = this;
	var compId = this.compId;
	var choseBtn = $("#"+compId).find('.j_chosebtn');
	choseBtn.click(function(){
		var parentLi = $(this).parents(".j_sub-item");
		parentLi.toggleClass('y_checked');
		var $group = parentLi.parents('.j_sub-products');
		computePrice($group);
		
	});
	
	function computePrice($group){
		var selected = $group.find('.j_sub-item.y_checked');
		var size = selected.size();
		var compRoot = $group.parents(".j_comp_root");
		var allMarketPrice = parseFloat(compRoot.attr("marketPrice"));
		var allShopPrice = parseFloat(compRoot.attr("shopPrice"));
		selected.each(function(ind,obj){
			var data = $(obj).data('subProduct');
			if(data ==null || data == undefined || data == ""){
				//取不到说明是同步加载，从attr中取
				var dataStr = $(obj).attr("data-subProduct");
				data = JSON.parse(dataStr);
			}
			allMarketPrice = floatCalFun.floatAdd(allMarketPrice, parseFloat(data.marketPrice));
			allShopPrice = floatCalFun.floatAdd(allShopPrice , parseFloat(data.shopPrice));
			
		});
		var reducePrice = floatCalFun.floatSubtract(allMarketPrice , allShopPrice);
		
		$group.parent().find('.j_selected').html(size);
		$group.parent().find('.j_selectedPrice').html("¥"+allShopPrice);
		$group.parent().find('.j_selectedMarketPrice').html("¥"+allMarketPrice);
		$group.parent().find('.j_reducePrice').html("¥"+reducePrice.toFixed(2));
		
	}
	
	
	//设置推荐搭配选择搭配商品框的宽度
	$("#"+compId).find(".j_sub-products ul").each(function(){
		$(this).width($(this).find("li").length*200);
	});
	
	//立即购买事件
	$("#"+compId).find(".j_buyGroup").on("click",function(){
		
		var $tab = $(this).parents(".j_content-item"); 
		if(that.loginTopic){
			CompMessage.publish(that.loginTopic,{},function(){
					var selected = 	$tab.find('.j_sub-item.y_checked');
					var productUuidAndSkuNoIdArr =  selected.map(function(ind,obj){
						var data = $(obj).data('subProduct');
						if(data ==null || data == undefined || data == ""){
							//取不到说明是同步加载，从attr中取
							var dataStr = $(obj).attr("data-subProduct");
							data = JSON.parse(dataStr);
						}
						return data.productUuid+"-"+data.skuNo
					}).get().join("|");
					
					$.getJSON(ContextPath+"/cart/addGroupProductTocart",
						{"productUuidAndSkuNoIdArr":productUuidAndSkuNoIdArr,"buyNum":1,"time":Math.random()},
						function(data) {
						  //跳转到购物车查看页面
						   window.location.href="/cart/cartshow";
						});
			});
		}
		
	});
	
}


/************************************** productGroup END **************************************/

/************************************** productDetail StART**************************************/


//组件定义
Comps.Productdetail = function(option){
	this.compId = option.compId;
	this.needAsyncInit = option.needAsyncInit;
	this.pageShow = option.pageShow;
	this.showAttribute = option.showAttribute;
	//运行期商品ID从URL中获取
	this.productUuid = this.getQueryString("productUuid");
	if(this.productUuid == null){
		//预览时  从属性配置中获取
		this.productUuid  = option.productUuid;
	}
}

Comps.Productdetail.prototype.getQueryString = function(name){
	 var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}

//组件渲染方法
Comps.Productdetail.prototype.init=function(){
	var that = this;
	if(this.needAsyncInit){
		$.getJSON( ContextPath+"/productdetail/getInitData",
			{productUuid:this.productUuid,pageShow:this.pageShow},
			function(data){
				if(data ){
					//生成页面HTML
					that.genHtml(data);
					that.initEvents();
					Utils.ajaxLoadComplate(that);
				}
			});
	}else{
		$(document).ready(function(){
			that.initEvents();
			Utils.ajaxLoadComplate(that);
		});
	}
}

//生成页面
Comps.Productdetail.prototype.genHtml = function(data){
	var compId = this.compId;
	var root = $("#"+compId);
	
	
	//表头内购物车
	//root.find(".j_addtocart").find(".j_product-detail-img").attr("src",data.smallImg);
	//root.find(".j_addtocart").find(".j_smallPrice").html(data.price);
	
	
	//商品介绍
	this.genDetailHtml(data);
	
	//售后服务
	root.find("#"+compId+"_detailname").html(data.afterService);
	
	//规格与包装
	this.genProdAttrs(data);
	//商品评价
	this.genAppraise(data);
}

//生成详情页签html
Comps.Productdetail.prototype.genDetailHtml = function(data){
	var compId = this.compId;
	var root = $("#"+compId);

	//描述
	root.find("#"+compId+"_detailimg").html(data.desc);
	//商品规格属性
	//this.genSpecAttribute(data);
}

//商品规格属性
Comps.Productdetail.prototype.genSpecAttribute = function(data){
	var compId = this.compId;
	var root = $("#"+compId);
	var ulEle = root.find("#"+compId+"_attribute");
	var liEle = ulEle.find(".j_attr-item");
	liEle.remove();
	if(data.productExtends){
		$.each(data.productExtends,function(index,attr){
			var temLi = liEle.clone();
			temLi.find(".j_attrName").html(attr.originalName);
			temLi.find(".j_attrValue").html(attr.attrValue);
			ulEle.append(temLi);
		});
	}else{
		//没有规格参数
		 $("#"+compId+"_attrWrap").remove();
	}
}

//生成规格与包装
Comps.Productdetail.prototype.genProdAttrs = function(data){
	var compId = this.compId;
	if(this.showAttribute){
		if(data.prodAttr !=null){
			$("#"+compId+"_prodAttrs-content").html(data.prodAttr);
		}else{
			$("#"+compId+"_prodAttrs-content").find(".j_content").html("");
		}
		
	}else{
		//删除标签页
		$("#"+compId+"_prodAttrs").remove();
		//删除标签页对应的内容
		$("#"+compId+"_prodAttrs-content").remove();
	}
	
}


//生成评价页签内容
Comps.Productdetail.prototype.genAppraise = function(data){
	var compId = this.compId;
	var comments = data.comments;
	//商品评价页签评价数
	$("#"+compId+"_appCount").html("("+comments.allCount+")");

	//好评率
	$("#"+compId+"_goodAppraiseRate").html(comments.goodAppraiseRate);
	//总评价人数
	$("#"+compId+"_allAppCount").html(comments.allCount);
	//好评率
	$("#"+compId+"_goodAppraiseRate2").html(comments.goodAppraiseRate+"%");
	$("#"+compId+"_goodProgress").css("width",comments.goodAppraiseRate+"%");
	
	//中评率
	$("#"+compId+"_middleAppraiseRate").html(comments.middleAppraiseRate+"%");
	$("#"+compId+"_middleProgress").css("width",comments.middleAppraiseRate+"%");
	//差评率
	$("#"+compId+"_badAppraiseRate").html(comments.badAppraiseRate+"%");
	$("#"+compId+"_badProgress").css("width",comments.badAppraiseRate+"%");
	
	//标签页各种评价数
	var tab = $("#"+compId+"_apptab");
	tab.find(".j_allAppCount").html(comments.allCount);
	//设置类型，用于点击tab事件，重新渲染评价
	tab.find("#"+compId+"_allAppraise").attr("data-type","0");
	//设置总页数，用于分页组件初始化
	tab.find("#"+compId+"_allAppraise").attr("data-totalPage",comments.wm.totalPage);
	
	
	tab.find(".j_goodAppCount").html(comments.goodCount);
	tab.find("#"+compId+"_goodAppraise").attr("data-type","1");
	
	tab.find(".j_middleAppCount").html(comments.middleCount);
	tab.find("#"+compId+"_normalAppraise").attr("data-type","2");
	
	tab.find(".j_badAppCount").html(comments.badCount);
	tab.find("#"+compId+"_lowAppraise").attr("data-type","3");
	
	tab.find(".j_picCount").html(comments.picCount);
	tab.find("#"+compId+"_showpicAppraise").attr("data-type","4");
	
	//评价内容
	this.genAppraiseContent(data.comments);

}
//评价内容
Comps.Productdetail.prototype.genAppraiseContent = function(comments){
	var compId = this.compId;
	var that = this;
	var divEle = $("#"+compId+"_evaluall");
	//重新渲染此部分需要移除之前的节点（点击好评，中评，差评，需要重新渲染内容）
	divEle.find(".j_remove").remove();
	if(comments.list && comments.list.length > 0){
		var itemEle = divEle.find(".j_item.j_template");
		$.each(comments.list,function(index,comment){
			var tempItem = itemEle.clone();
			//模板本身隐藏，克隆后 展示出来
			tempItem.css("display","block");
			//添加样式j_remove 以便于重新渲染时 删除这些节点
			tempItem.removeClass('j_template').addClass("j_remove");
			
			// 生成评论人信息
			//评论人头衔
			var defaultImg = ContextPath + "/static/usercenter/img/default.png";
			if(comment.customerImage){
				if(comment.customerImage.substr(0,4)!="http"){
					tempItem.find(".j_customerImg").attr("src",defaultImg);
				}else{
					tempItem.find(".j_customerImg").attr("src",comment.customerImage);
				}
				//tempItem.find(".j_customerImg").attr("src","/static/usercenter/img/default.png");
			}else{
				tempItem.find(".j_customerImg").attr("src",defaultImg);
			}
			//会员名称
			tempItem.find(".j_customerName").html(comment.customerName);
			tempItem.find(".j_appTime").html(comment.productAppraise.appTime);
			//会员评分
			tempItem.find(".j_appScore").css("width",(comment.productAppraise.appScore/5)*100+"%");
			//评论内容
			tempItem.find(".j_appContent").html(comment.productAppraise.appContent);
			//会员购买的规格
			var parent = tempItem.find(".j_attr");
			var attrName = parent.find(".j_attrName");
			var attrValue = parent.find(".j_attrValue");
			attrName.remove();
			attrValue.remove();
			$.each(comment.spec,function(index,attr){
				 that.genAppContentBuyAttr(attr,attrName,attrValue,parent);
			});
			
			//会员的晒单信息
			that.genCommentPic(comment,tempItem);
			
			divEle.append(tempItem);
		});
	}else{
		divEle.find(".j_nothing").clone().css("display","block").removeClass("j_template").addClass("j_remove").appendTo(divEle);
		 //$("#"+$_compId_$+"_page").css();
	}


}

//评价人的购买信息
Comps.Productdetail.prototype.genAppContentBuyAttr = function(attr,attrName,attrValue,parent){
	var tmpAttrName = attrName.clone();
	var tmpAttrValue = attrValue.clone();
	tmpAttrName.html(attr.name+":");
	tmpAttrValue.html(attr.value);
	parent.append(tmpAttrName);
	parent.append(tmpAttrValue);
}

//评价人的晒图信息
Comps.Productdetail.prototype.genCommentPic = function(comment,tempItem){
	var wrap = tempItem.find(".j_pics");
	if(comment && comment.picList && comment.picList.length > 0){
		var ulEle = wrap.find(".j_photos-thumb");
		var liEle = ulEle.find(".j_photos-thumb-item");
		liEle.remove();
		$.each(comment.picList,function(index,pic){
			var tmpLi = liEle.clone();
			tmpLi.attr("data-src",pic.picUrl).find(".j_img").attr("src",pic.picUrl);
			ulEle.append(tmpLi);
		});
	}else{
		wrap.remove();
	}
}

//初始化 分页
Comps.Productdetail.prototype.initPaging=function(type,totalPage){
	var that = this;
	var page = $("#"+this.compId+"_page");
	var pageShow = this.pageShow;
	layui.use(['laypage', 'layer'], function(){
	  var laypage = layui.laypage,layer = layui.layer;
	  laypage({
		    cont: page,
		    pages: totalPage,
		    skip: true,
		    jump: function(obj, first){
			    	if(!first){
			    		//初始化的时候也会执行次方法，如果不是第一次渲染分页，则只需要重新渲染评价内容
			    		that.getCommentPage(type,obj.curr,pageShow,false);
			    	}else{
			    		//首次渲染，什么也不做
			    	}
		      }
		  });
	});

}
//分页获取评论信息
Comps.Productdetail.prototype.getCommentPage=function(type,nowPage,pageShow,isInitPage){
	var that = this;
	$.getJSON( ContextPath+"/productdetail/getComment",
		{"productUuid":this.productUuid,"type":type,"nowPage":nowPage,"pageShow":pageShow},
		function(data){
			if(data.return_code=="0" ){
				that.genAppraiseContent(data);
				if(isInitPage){
					//如果是点击了页签 好评，中评，则分页组件需要重新渲染，否则只点击上一页，下一页不需要重新渲染
					that.initPaging(type,data.wm.totalPage);
				}
			}
	});
}
//固定表头
Comps.Productdetail.prototype.fixTop = function(){
	var compId = this.compId;
	var compTop = $("#"+compId).offset().top;
	var header =  $("#"+compId+"_header") ;
	window.onscroll = function(){ 
	    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;  
	    if(  scrollTop >=  compTop) { 
	    	header.removeClass("y_pdtabbox").addClass("y_producttabfix");
	    } else { 
	    	header.removeClass("y_producttabfix").addClass("y_pdtabbox");
	    } 
	} 
}

//点击小图，展示大图
Comps.Productdetail.prototype.showPhoto = function(liEle){
	$(liEle).siblings().removeClass("j_current");
	$(liEle).toggleClass("j_current");
	var viewer = $(liEle).parents(".j_photos").find(".j_photo-view");
	viewer.css("display",$(liEle).hasClass("j_current")?"block":"none");
	var src = $(liEle).attr("data-src");
	viewer.find("img").attr("src",src);
	
	//点开，如果是 第一张或者最后一张 隐藏上一页或者下一页
	/**
	var photos = $(el).parents(".j_photos");
	var photoSize = photos.find(".j_photos-thumb-item").length;
	var currentPhoto = photos.find(".j_photos-thumb-item.j_current");
	var currentIndex = currentPhoto.index();
	if(currentIndex == 0){
		//第一张图 隐藏
	}
	**/
}

//点击大图片收缩起来
Comps.Productdetail.prototype.hidePhoto = function(el){
	$(el).parents(".j_photos").find(".j_photos-thumb-item").removeClass("j_current");
	$(el).css("display","none");
}

Comps.Productdetail.prototype.nextPhoto = function(el,next,e){
	var photos = $(el).parents(".j_photos");
	var photoSize = photos.find(".j_photos-thumb-item").length;
	var currentPhoto = photos.find(".j_photos-thumb-item.j_current");
	var currentIndex = currentPhoto.index();

	var $next = photos.find(".j_photos-thumb-item").eq(currentIndex+next);
	if(currentIndex+next == photoSize ){
		$next = photos.find(".j_photos-thumb-item").eq(0);
	}
	//移动到下一个
	photos.find(".j_big-photo").attr("src",$next.attr("data-src"));
	//先移除j_current,在给下一个加上j_current
	photos.find(".j_photos-thumb-item").removeClass("j_current");
	$next.addClass("j_current");
		
	e.stopPropagation();
}


//初始化事件
Comps.Productdetail.prototype.initEvents = function(){
	var compId = this.compId;
	var that = this;
	var tab = $("#"+compId+"_apptab");
	//页签事件
	tab.find("a").click(function(){
		var type = $(this).attr("data-type");
		that.getCommentPage(type,"0",that.pageShow,true);
	});
	
	//第一次加载页面,展示全部评价，分页首次渲染
	var totalPage = parseInt($("#"+compId+"_allAppraise").attr("data-totalPage"));
	this.initPaging("0", totalPage);
	this.fixTop();
	
	//点击晒图，展示大图
	$(document.body).on("click", ".j_photos-thumb-item", function(){
		that.showPhoto(this);
	});
	//点击大图，收起事件
	$(document.body).on("click", ".j_photo-view", function(){
		that.hidePhoto(this);
	});
	//点击上一张图，下一张图事件
	$(document.body).on("click", ".j_photo-view-nav-prev", function(e){
		that.nextPhoto(this,-1,e);
	});
	$(document.body).on("click", ".j_photo-view-nav-next", function(e){
		that.nextPhoto(this,1,e);
	});
	
	$("#"+compId+" .main_wrap").find("li a").on("click",function(e){
		var compTop = $("#"+compId).offset().top;
		var activeHeight = $("#"+compId+" .main_wrap").find("li.active").height();
		window.scrollTo(0,compTop-7);
		// 7是 active的高度和 正常的高度差
		//var height =  $("#"+compId+" .main_wrap").find("li").not(".active").height();
		//var pad = activeHeight -height;
		//window.scrollTo(0,compTop-pad);
	});
	
}


/************************************** productDetail END**************************************/




/************************************** productTab START**************************************/

Comps.ProductTab = function(option){
	this.compId = option.config.compId;
	this.needAsyncInit = option.config.needAsyncInit;
	this.showStyle = option.config.showStyle;
	this.tabsJson = JSON.stringify(option.tabsJson);
	this.productDetailUrl = option.config.productDetailUrl;
	this.loginTopic = option.config.loginTopic;
	this.collectUrl = option.config.collectUrl;
}

//初始化保存模板
Comps.ProductTab.prototype.initTemplate= function(){
	//保存 详情模板，防止在嵌套循环中模板被删除掉
	var root = $("#"+this.compId+"-products");
	var productDeail = root.find(".j_product-detail");
	var productTmplate = productDeail;
	productDeail.remove();
	
	//商品组 模板，8个商品一组，产生轮播效果（8个商品在一个LI内）
	var productLi = root.find(".j_tab-product-page-group");
	var productLiTmplate = productLi;
	productLi.remove();
	
	//标签页内容模板，每个标签页对应一个标签页内容
	var tabContent = root.find(".j_tab-content-wrap");
	var tabContentTemplate = tabContent;
	tabContent.remove();
	
	return {"productTmplate":productTmplate,"productLiTmplate":productLiTmplate,"tabContentTemplate":tabContentTemplate};
}

Comps.ProductTab.prototype.init= function(){
	var that = this;
	if(this.needAsyncInit){
		$.getJSON( ContextPath+"/producttab/getInitData",// "/producttab/getInitData" "/syscomps/pages/producttab/initData.json"
			{tabJson:this.tabsJson},
			function(data){
				if(data ){
					//先初始化模板，生成页面需要这些模板
					var template = that.initTemplate();
					//生成页面HTML
					that.genHtml(data,template);
					that.initEvents();
					Utils.ajaxLoadComplate(that);
				}
			});
	}else{
		$(document).ready(function(){
			that.initEvents();
			Utils.ajaxLoadComplate(that);
		});
	}
}

Comps.ProductTab.prototype.genHtml= function(data,template){
	var compId = this.compId;
	var that = this;
	//标签页tab
	var tabs = $("#"+compId+"-tabs");
	var liEl = tabs.find(".j_product-tab");
	liEl.remove();
	
	var tabContents = $("#"+compId+"-products");
	var tabContentTemplate = template.tabContentTemplate;
	
	for(var i =0, len = data.length; i < len ; i++){
		var tabData = data[i];
		var tabContentId = compId+"-tab-content-"+i;
		//生成一个标签页
		var tmpLi = liEl.clone();
		tmpLi.attr("href","#"+tabContentId);//标签页锚向标签页内容容器
		tmpLi.find(".j_tab-name").html(tabData.tabName);
		if(i==0)tmpLi.addClass("on");
		tabs.append(tmpLi);
		//生成一个标签页对应的内容容器
		var tmpTabContent  = tabContentTemplate.clone();
		tmpTabContent.attr("id",tabContentId);
		//常规展示 不需添加slide
		if(that.showStyle == "1")tmpTabContent.addClass("m-noslide");
		//向容器里面添加数据
		that.genTabProducts(tabData.products,tmpTabContent,template);
		tabContents.append(tmpTabContent);
	}
}

//根据 商品 生成一个标签页中的 商品
Comps.ProductTab.prototype.genTabProducts = function(products,container,template){
	var pagingContainerUl = container.find("ul.j_tab-product-page-wrap");
	var productGroupLi = template.productLiTmplate;
	var groups = this.groupProducts(products);
	for(var j = 0 ; j < groups.length ; j++){
		//循环每个分组
		var groupProducts = groups[j];//每个分组内的商品
		//创建分组
		var tmpGroupLi = productGroupLi.clone();
		//往分组内添加 商品数据
		this.genOneGroupHtml(groupProducts,tmpGroupLi,template);
		//将新生成的li追加到Ul下
		pagingContainerUl.append(tmpGroupLi);
	}

}

Comps.ProductTab.prototype.genOneGroupHtml = function(products,tmpGroupLi,template){
	//商品模板
	var productDetail = template.productTmplate;
	var that = this;
	for(var i = 0 ,len = products.length ; i < len ; i++){
		var product = products[i];
		var tmpProduct = productDetail.clone();
		tmpProduct.find(".j_product-name").html(product.productName);
		tmpProduct.find(".j_product-price").html(product.price);
		
		var link = ContextPath+that.productDetailUrl+"&productUuid="+product.productUuid;
		tmpProduct.find("a.j_product-link").attr("href",link);
		tmpProduct.find("a.j_product-collect").attr("data-id",product.productUuid);
		tmpProduct.find(".j_product-photo").attr("src",product.pic);
		tmpGroupLi.append(tmpProduct);
	}
}


//将 商品分组，8个商品为一组，获得一个二位数组
Comps.ProductTab.prototype.groupProducts = function(products){
	var res = new Array();
	for(var i = 0 ,len = products.length ; i < len ; i++){
		var arr = null;
		if((i+1) % 8 == 1){
			arr  = new Array();
			res.push(arr);
		}else{
			arr = res[res.length-1];
		}
		arr.push(products[i]);
	}
	return res;
}

// 商品收藏事件
Comps.ProductTab.prototype.collectProduct=function(uuid){
	var that=this;
	var compId = this.compId;
	var url = ContextPath+"/collectionProductComp/collectProduct";
	var collectCenterUrl = ContextPath + this.collectUrl;
	var $returnMessage = $("#"+compId+"_returnMessage");
	var $collectNum = $("#"+compId+"_collectNum");
	//设置收藏中心的URL
	$("#"+compId+"_collectUrl").attr("href",collectCenterUrl);
	$.ajax({
		type : "GET",
		url : url,
		data : {
			productUuid : uuid,
			ranNum : Math.random()
		},
		dataType : "json",
		async : false,
		success : function(data) {
			if(data.state=="1"){
				$collectNum.html(data.count);
				$returnMessage.html("收藏成功");
			}
			else if (data.state=="2"){
				$collectNum.html(data.count);
				$returnMessage.html("收藏失败");
			}
			else if (data.state=="3"){
				$collectNum.html(data.count);
				$returnMessage.html("您已经收藏过改商品了");
			}
			
			$("#"+compId+"_modal-collect-form").modal('show');
		
		}
	})
}

Comps.ProductTab.prototype.initEvents= function(){
	var that = this;
	//轮播slider
	if(this.showStyle=="2"){
		 $("#"+this.compId+" .j_tab-content-wrap").each(function(){
			 $(this).slide({mainCell:".itembd ul",effect:"leftLoop",prevCell:".sprev",nextCell:".snext"});
		 });
	}
	//外层slider
	$("#"+this.compId+".m-productmc-slider").slide({});
	
	//商品收藏
	$("#"+this.compId).find(".j_product-collect").on("click",function(){
		var productUuid = $(this).attr("data-id");
		if(that.loginTopic){
			CompMessage.publish(that.loginTopic,{},function(){
				that.collectProduct(productUuid);
			});
		}
		
		
	});
}
/************************************** productTab END**************************************/


/************************************** slideProduct START**************************************/

Comps.SlideProducts = function(option){
	this.compId = option.compId;
	this.needAsyncInit = option.needAsyncInit;
	this.productUuids = option.productUuids;
	this.productDetailUrl = option.productDetailUrl;
	this.slideSpeed = option.slideSpeed;
	this.slideAuto = option.slideAuto;
	this.interTime = option.interTime;
	this.loginTopic = option.loginTopic;
	this.dataCount = 0;
	this.collectUrl = option.collectUrl;
}

Comps.SlideProducts.prototype.init=function(){
	var that = this;
	if(this.needAsyncInit){
		$.getJSON( ContextPath+"/slideproducts/ajaxLoadData",// "/producttab/getInitData" "/syscomps/pages/producttab/initData.json"
			{productUuids:this.productUuids},
			function(data){
				if(data ){
					//生成页面HTML
					var template = that.initTemplate();
					that.genHtml(data,template);
					that.initEvents();
					Utils.ajaxLoadComplate(that);
				}
			});
	}else{
		$(document).ready(function(){
			that.initEvents();
			Utils.ajaxLoadComplate(that);
		});
	}
}

Comps.SlideProducts.prototype.initTemplate=function(){
	var compId = this.compId;
	//保存 详情模板，防止在嵌套循环中模板被删除掉
	var root = $("#"+this.compId+"-products");
	var productDeail = root.find(".j_product-detail");
	var productTmplate = productDeail;
	productDeail.remove();
	
	//商品组 模板，8个商品一组，产生轮播效果（8个商品在一个LI内）,轮播LI
	var productLi = root.find(".j_tab-product-page-group");
	var productLiTmplate = productLi;
	productLi.remove();
	
	return {"productTmplate":productTmplate,"productLiTmplate":productLiTmplate};
}

Comps.SlideProducts.prototype.genHtml= function(products,template){
	if(products&& products.length>0)
	{
		this.dataCount = products.length;
		var compId = this.compId;
		var that = this;
		var pagingContainerUl = $("#"+compId+"-paging-container");
		
		var productGroupLi = template.productLiTmplate;
		var groups = this.groupProducts(products);
		for(var j = 0 ; j < groups.length ; j++){
			//循环每个分组
			var groupProducts = groups[j];//每个分组内的商品
			//创建分组
			var tmpGroupLi = productGroupLi.clone();
			//往分组内添加 商品数据
			this.genOneGroupHtml(groupProducts,tmpGroupLi,template);
			//将新生成的li追加到Ul下
			pagingContainerUl.append(tmpGroupLi);
		}
	}else{
		//没有配置数据
		console.log("没有配置数据");
	}
	
}

Comps.SlideProducts.prototype.genOneGroupHtml = function(products,tmpGroupLi,template){
	//商品模板
	var productDetail = template.productTmplate;
	var that = this;
	for(var i = 0 ,len = products.length ; i < len ; i++){
		var product = products[i];
		var tmpProduct = productDetail.clone();
		tmpProduct.find(".j_product-name").html(product.productName);
		tmpProduct.find(".j_product-price").html(product.price);
		
		var link = ContextPath+that.productDetailUrl+"&productUuid="+product.productUuid;
		tmpProduct.find("a.j_product-link").attr("href",link);
		tmpProduct.find("a.j_product-collect").attr("data-id",product.productUuid);
		tmpProduct.find(".j_product-photo").attr("src",product.pic);
		tmpGroupLi.append(tmpProduct);
	}
}

//将 商品分组，8个商品为一组，获得一个二位数组
Comps.SlideProducts.prototype.groupProducts = function(products){
	var res = new Array();
	for(var i = 0 ,len = products.length ; i < len ; i++){
		var arr = null;
		if((i+1) % 8 == 1){
			arr  = new Array();
			res.push(arr);
		}else{
			arr = res[res.length-1];
		}
		arr.push(products[i]);
	}
	return res;
}

//商品收藏事件
Comps.SlideProducts.prototype.collectProduct=function(uuid){
	var that=this;
	var compId = this.compId;
	var url = ContextPath+"/collectionProductComp/collectProduct";
	var collectCenterUrl = ContextPath + this.collectUrl;
	var $returnMessage = $("#"+compId+"_returnMessage");
	var $collectNum = $("#"+compId+"_collectNum");
	//设置收藏中心的URL...
	$("#"+compId+"_collectUrl").attr("href",collectCenterUrl);
	$.ajax({
		type : "GET",
		url : url,
		data : {
			productUuid : uuid,
			ranNum : Math.random()
		},
		dataType : "json",
		async : false,
		success : function(data) {
			if(data.state=="1"){
				$collectNum.html(data.count);
				$returnMessage.html("收藏成功");
			}
			else if (data.state=="2"){
				$collectNum.html(data.count);
				$returnMessage.html("收藏失败");
			}
			else if (data.state=="3"){
				$collectNum.html(data.count);
				$returnMessage.html("您已经收藏过改商品了");
			}
			
			$("#"+compId+"_modal-collect-form").modal('show');
		
		}
	})
}

Comps.SlideProducts.prototype.initEvents = function(){
	var that = this;
	var speed = this.slideSpeed;//轮播速度
	var auto = this.slideAuto;//是否自动轮播
	var interTime = this.interTime;//自动轮播时 轮播间隔
	$("#"+this.compId+" .j_tab-content-wrap").each(function(){
		 $(this).slide({mainCell:".itembd ul",effect:"leftLoop",prevCell:".sprev",nextCell:".snext",
			 delayTime:speed,
			 autoPlay:auto ,
			 interTime:interTime
		});
	 });
	//商品收藏
	$("#"+this.compId).find(".j_product-collect").on("click",function(){
		var productUuid = $(this).attr("data-id");
		if(that.loginTopic){
			CompMessage.publish(that.loginTopic,{},function(){
				that.collectProduct(productUuid);
			});
		}
		
	});
}

/************************************** slideProduct END**************************************/


/*************************************** slideAds START *************************************/

Comps.SlideAds = function(option) {
    this.needAsyncInit = option.needAsyncInit;
    this.compId = option.compId;
	this.slideSpeed = option.slideSpeed;
	this.interTime = option.interTime;
    this.adUuid = option.adUuid;
    this.defineHeight = option.defineHeight;
    this.marginBottom = option.marginBottom;
    this.alt = option.alt;
    this.videoTime = option.videoTime;
}
//轮播效果触发方法
Comps.SlideAds.prototype.slide = function() {

	var speed = this.slideSpeed;//轮播速度
	var interTime = this.interTime;//自动轮播时 轮播间隔
    //jQuery(".m-bannerslider").slide({mainCell:".bd ul",effect:"leftLoop",autoPlay:true,prevCell:".bnprev",nextCell:".bnnext",  delayTime:speed, interTime:interTime });
	//banner切换
	$('.index_banner .flexslider').flexslider({
		controlsContainer:".slider_fullscreen_control",
		animation: "slide",
		animationLoop: true,
		pauseOnAction: true,
		pauseOnHover: false,
		slideshowSpeed: interTime
	});
}
//页面初始化方法
Comps.SlideAds.prototype.init = function() {
    var that = this;
    var videoTime = that.videoTime;
    var windW = $(window).width();
    if(windW <= 992) {
        var xc =  windW / 1920 * 1080;
        $('#movie').height(xc);
    }

    //banner切换
    var oSj = parseFloat(videoTime)*parseInt(1000) ;
    var slidOsj = parseInt(oSj)-parseInt(600);
    var bar = $('.banner-bar');
    $('.index_banner .flexslider').flexslider({
        controlsContainer:".slider_fullscreen_control",
        animation: "slide",
        animationLoop: true,
        pauseOnAction: false,
        pauseOnHover: false,
        slideshowSpeed: oSj,
        animationDuration: 600,
        directionNav: true,
        start:function () {
            $('.slider_cont img').css('opacity','1')
            var videos = $('.flex-active-slide').attr('data-type')
            if(videos == 'videos') {
                $('.flex-active-slide video').get(0).play();

            }

        },
        after: function () {
            barAniMate(slidOsj)
        },

    });
    barAniMate(oSj)
    //进度条函数动画效果
    function barAniMate(timer){
        bar.animate({width:'100%'},timer,function(){
            $(this).css('width','1px');
        });
    }



/*if(this.adUuid==""||this.adUuid==undefined||this.adUuid==null){
    Utils.ajaxLoadComplate(that);
    return;
}
if(this.needAsyncInit){
    $.ajax({
        type: "GET",
        url: ContextPath+"/slideAds/ajaxLoadData",
        data: {adUuid :this.adUuid},
        dataType: "json",
        success: function(data) {
            //1.获取返回的广告、图片url
            var listData= eval(data);
            var urlList;

      *//*      //2.获取锚点所在ul，并克隆节点
            var fgUl = $("#slideBox_fgUl");
            var fgUlClone = fgUl.clone();
            var fgLiClone = fgUl.children(0).clone();
            fgUlClone.empty();*//*

            //3、获取广告图片所在ul，并克隆节点
            var bgUl = $("#slideBox_bgUl");
            var bgUlClone = bgUl.clone();
            bgUlClone.empty();
            var bgLiClone = bgUl.children(0);

            //4、生成锚点及广告图片节点
            var adUrl = "";
            var picUrl = "";
            for(var i=0;i<listData.length;i++){
                var bgLi = bgLiClone.clone();
               *//* var fgLi = fgLiClone.clone();
                if(i!=0){
                    fgLi.removeClass();
                }*//*
                //fgUlClone.append(fgLi[0].outerHTML);
                adUrl = listData[i];
                urlList = adUrl.split(";");
                if(urlList.length==2){
                    adUrl = urlList[1];
                    picUrl = urlList[0];
                }else if(urlList.length==1){
                    picUrl = urlList[0];
                    adUrl = "javascript:void(0)";
                }
                bgLi.children(0).attr("href", adUrl);
                bgLi.children(0).children(0).attr("src", picUrl);
                bgLi.children(0).children(0).attr("alt", this.alt);
                bgUlClone.append(bgLi[0].outerHTML);
            }

            //5、替换原有节点
            //fgUl.replaceWith(fgUlClone);
            bgUl.replaceWith(bgUlClone);
            that.slide();

            if(this.defineHeight != null && this.defineHeight != ""){
                $(".index_banner").css("height", this.defineHeight + "px");
            }

            if(this.marginBottom != null && this.marginBottom != ""){
                $(".index_banner").css({"height": this.defineHeight+"px","margin-bottom":this.marginBottom+"px"});
            }
            Utils.ajaxLoadComplate(that);
        }
    });
}else{
    //同步加载，初始化事件
    that.slide();
    Utils.ajaxLoadComplate(that);
}*/

}
/*************************************** slideAds END *************************************/


